﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Newtonsoft.Json;
using Viettel.VOFFICE.DAO.Enums;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class RolesController : BaseController
    {

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult GetList(string id)
        {
            //var unitOfwork = new Viettel.VOFFICE.DAO.DAL.UnitOfWork();
            if (!string.IsNullOrWhiteSpace(id))
            {
                var role = new RoleModel(unitOfWork.RoleRepository.GetByName(id));
                return Json(role, JsonRequestBehavior.AllowGet);
            }

            var roles = unitOfWork.RoleRepository.Get().Select(o => new RoleModel(o)).ToList();
            var result = Json(roles, JsonRequestBehavior.AllowGet);
            return result;
        }

        // Update Role
        [AcceptVerbs(HttpVerbs.Put)]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateRole(string id, RoleModel roleModel)
        {
            //var unitOfwork = new Viettel.VOFFICE.DAO.DAL.UnitOfWork();
            var role = unitOfWork.RoleRepository.GetByName(id);
            if (role != null && roleModel.RoleId != null)
            {
                role.RoleName = roleModel.RoleName;
                role.Description = roleModel.Description;
                role.RoleDisplayName = roleModel.RoleDisplayName;
                role.LoweredRoleName = roleModel.RoleName.ToLower();
                unitOfWork.RoleRepository.Update(role);
            }
            else
            {
                role = new aspnet_Roles()
                {
                    RoleId = System.Guid.NewGuid(),
                    RoleName = roleModel.RoleName,
                    ApplicationId = ApplicationId,
                    RoleDisplayName = roleModel.RoleDisplayName,
                    Description = roleModel.Description,
                    LoweredRoleName = roleModel.RoleName.ToLower()
                };
                unitOfWork.RoleRepository.Insert(role);
                roleModel.RoleId = role.RoleId.ToString();
            }

            return Json(new RoleModel(role), JsonRequestBehavior.DenyGet);
        }

        // Insert Role
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddRole(RoleModel roleModel)
        {
            //var unitOfwork = new Viettel.VOFFICE.DAO.DAL.UnitOfWork();
            var role = new aspnet_Roles()
                           {
                               RoleId = System.Guid.NewGuid(),
                               RoleName = roleModel.RoleName,
                               ApplicationId = ApplicationId,
                               RoleDisplayName = roleModel.RoleDisplayName,
                               Description = roleModel.Description,
                               LoweredRoleName = roleModel.RoleName.ToLower(),
                               IsActive = true,//TODO:lấy từ client
                               CreatedAt = DateTime.Now,
                               UpdatedAt = DateTime.Now,
                               Type = (int)RoleType.None,//TODO:lấy từ client
                           };
            unitOfWork.RoleRepository.Insert(role);
            roleModel.RoleId = role.RoleId.ToString();
            return Json(roleModel, JsonRequestBehavior.DenyGet);
        }
        //Delete Role
        [AcceptVerbs(HttpVerbs.Delete)]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteRole(string id)
        {
            var role = unitOfWork.RoleRepository.GetByName(id);
            unitOfWork.RoleRepository.Delete(role);
            return Json(null, JsonRequestBehavior.DenyGet);
        }

        //Get User By RoleName
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult GetUserList(string id)
        {
            string[] userinRole = Roles.GetUsersInRole(id);
            var allUser = Membership.GetAllUsers();
            List<UserInRoleModel> uiModel = new List<UserInRoleModel>();
            foreach (var userItem in allUser)
            {
                MembershipUser user = (MembershipUser)userItem;
                UserInRoleModel model = new UserInRoleModel()
                {
                    UserName = user.UserName,
                    RoleName = id,
                    IsInRole = userinRole.Contains(user.UserName)
                };
                uiModel.Add(model);
            }
            return Json(uiModel.Select(x => new { UserName = x.UserName, RoleName = x.RoleName, IsInRole = x.IsInRole }).ToList(), JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AssignUser(string id, string collection)
        {
            List<UserInRoleModel> ltdata = JsonConvert.DeserializeObject<List<UserInRoleModel>>(collection);
            string[] assignUser = ltdata.Where(s => s.IsInRole == true).Select(x => x.UserName).ToArray();
            string[] existsuser = Roles.GetUsersInRole(id);
            if (existsuser != null && existsuser.Length > 0)
                Roles.RemoveUsersFromRole(existsuser, id);
            if (assignUser != null && assignUser.Length > 0)
                Roles.AddUsersToRole(assignUser, id);
            return Json(null);
        }
    }
}
